package com.ja.openchat.ui.message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.databinding.Observable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.google.gson.JsonObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentMessageBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.ui.message.adapter.RecentMessageListAdapter;
import com.ja.openchat.viewmodels.MsgViewModel;
import com.ja.openchat.views.BottomSelectionDialog;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.ContactGroupSendDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.DensityUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class MsgFragment extends BaseFragment<FragmentMessageBinding, MsgViewModel> implements DoubleClickListener {

    private Context mContext;
    public RecentMessageListAdapter recentMessageListAdapter;
    private LinearLayoutManager linearLayoutManager;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return R.layout.fragment_message;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }


    @Override
    public MsgViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        MsgViewModel msgViewModel = ViewModelProviders.of(this, factory).get(MsgViewModel.class);
        msgViewModel.setContext(mContext);
        return msgViewModel;
    }

    //创建侧滑菜单
    public final SwipeMenuCreator creator = (leftMenu, rightMenu, position) -> {
        ChatInfo chat = recentMessageListAdapter.getItem(position);
        String deleteLable = getString(R.string.delete_text);
        if(chat.isSuperGroup()){
            SuperGroupInfo superGroupInfo = recentMessageListAdapter.getSuperGroupByChatId(chat);
            if(superGroupInfo!=null){
                if(superGroupInfo.isPublicGroup()){
                    deleteLable = getString(R.string.leave_group_text);
                }else if(superGroupInfo.status!=null&&superGroupInfo.status.isMyCreatorGroup()){
                    deleteLable = getString(R.string.disband_the_group);
                }
            }
        }
        SwipeMenuItem noticeItem = new SwipeMenuItem(mContext)
                .setBackgroundColorResource(R.color.color_0DBFC0FF)
                .setImage(chat.default_disable_notification ? R.mipmap.image_open_notice : R.mipmap.image_close_notice)
                .setText(chat.default_disable_notification ? mContext.getString(R.string.open_notifiy) : mContext.getString(R.string.close_notifiy))
                .setTextColor(Color.WHITE)
                .setTextSize(13)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setWidth(DensityUtil.dp2px(55));
        SwipeMenuItem topItem = new SwipeMenuItem(mContext)
                .setBackgroundColorResource(R.color.me_nick_name_color_text_sub)
                .setImage(chat.is_pinned ? R.mipmap.image_no_top : R.mipmap.image_top)
                .setText(getString(chat.is_pinned ? R.string.cancle_top_text : R.string.top_text))
                .setTextColor(Color.WHITE)
                .setTextSize(13)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setWidth(DensityUtil.dp2px(55));
        SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
                .setBackgroundColorResource(R.color.color_fd4e57)
                .setImage(R.mipmap.image_delete)
                .setText(deleteLable)
                .setTextColor(Color.WHITE)
                .setTextSize(13)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setWidth(DensityUtil.dp2px(55));
        rightMenu.addMenuItem(topItem);
        rightMenu.addMenuItem(noticeItem);
        rightMenu.addMenuItem(deleteItem);
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEmptyEvent(String message){

    }

    @Override
    public void initView() {
        //显示状态
        viewModel.refreshConnectionState();
        //
        viewModel.resetChatList();
        linearLayoutManager = new LinearLayoutManager(mContext);
        binding.rv.setLayoutManager(linearLayoutManager);
        recentMessageListAdapter = new RecentMessageListAdapter(R.layout.adapter_history_message_list, viewModel.chatList.get());
//        recentMessageListAdapter.setUseEmpty(true);
//        recentMessageListAdapter.setEmptyView(R.layout.empty_message_view);
        //设置侧滑菜单列表
        binding.rv.setSwipeMenuCreator(creator);
        viewModel.setadapter(recentMessageListAdapter);

//        View emptyView = getLayoutInflater().inflate(R.layout.empty_message_view,binding.rv,false);
        //侧滑事件监听回调
        binding.rv.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            switch (menuBridge.getPosition()) {
                case 0://置顶
                    menuBridge.closeMenu();
                    viewModel.clickPin(MsgFragment.this, viewModel.chatList.get().get(adapterPosition));
                    break;
                case 1://关闭通知
                    menuBridge.closeMenu();
                    viewModel.clickMute(MsgFragment.this, viewModel.chatList.get().get(adapterPosition));
                    break;
                case 2://删除
                    menuBridge.closeMenu();
                    viewModel.clickDelete(MsgFragment.this, viewModel.chatList.get().get(adapterPosition));
                    break;
            }
        });

        binding.rv.setAdapter(recentMessageListAdapter);
        recentMessageListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ChatActivity.startActivity(getContext(), recentMessageListAdapter.getItem(position));
            }
        });
        recentMessageListAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ChatInfo chatInfo = recentMessageListAdapter.getItem(position);
                String deleteLable = getString(R.string.delete_text);
                if(chatInfo!=null&&chatInfo.isSuperGroup()){
                    SuperGroupInfo superGroupInfo = recentMessageListAdapter.getSuperGroupByChatId(chatInfo);
                    if(superGroupInfo!=null){
                        if(superGroupInfo.isPublicGroup()){
                            deleteLable = getString(R.string.leave_group_text);
                        }else if(superGroupInfo.status!=null&&superGroupInfo.status.isMyCreatorGroup()){
                            deleteLable = getString(R.string.disband_the_group);
                        }
                    }
                }
                new XPopup.Builder(mContext)
                        .hasShadowBg(true)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .borderRadius(10)
                        .atView(view)
                        .asCustom(new BottomSelectionDialog(getContext(), chatInfo,deleteLable, new BottomSelectionDialog.OnItemClickListner() {
                            @Override
                            public void clickPostion(int postion, ChatInfo chatInfo) {
                                switch (postion) {
                                    case 0://置顶
                                        viewModel.clickPin(MsgFragment.this, chatInfo);
                                        break;
                                    case 1://关闭通知
                                        viewModel.clickMute(MsgFragment.this, chatInfo);
                                        break;
                                    case 2://删除
                                        viewModel.clickDelete(MsgFragment.this, chatInfo);
                                        break;
                                }
                            }
                        })).show();

                return true;
            }
        });
//        viewModel.fragmentTitle.set(getString(R.string.fragment_title));
        binding.toolbar.ivBarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(mContext)
                        .offsetX(-2)
                        .offsetY(SizeUtils.dp2px(30))
                        .hasShadowBg(false)
                        .isLightStatusBar(true)
                        .atView(binding.toolbar.ivBarRight)
                        .asAttachList(new String[]{getString(R.string.add_friend_text), getString(R.string.create_group), getString(R.string.create_prive_chat), getString(R.string.scan_text)}
                                , new int[]{R.mipmap.image_add_buddy, R.mipmap.image_add_group, R.mipmap.private_chat, R.mipmap.image_scan},
                                (position, text) -> {
                                    switch (position) {
                                        case 0:
                                            startActivity(AddContactActivity.class);
                                            break;
                                        case 1:
//                                            ContactChooseActivity.startWithCreateSuperGroup((Activity) mContext);
                                            createGroup();
                                            break;
                                        case 2:
                                            ContactChooseActivity.start(mContext, ContactChooseActivity.ContactChooseType.ContactChooseType_CreateSecreat);
                                            break;
                                        case 3: {
                                            IntentIntegrator integrator = new IntentIntegrator((Activity) mContext);
                                            integrator.setPrompt("");
                                            integrator.setBeepEnabled(false);
                                            integrator.setBarcodeImageEnabled(false);
                                            integrator.setOrientationLocked(false);
                                            integrator.setCaptureActivity(ScanActivity.class);
                                            integrator.initiateScan();
                                        }
                                        break;
                                    }
                                }, R.layout.dialog_attach_list_popu, R.layout.dialog_attach_item).show();
            }
        });

        if (!NotificationManagerCompat.from(mContext).areNotificationsEnabled()) {
            binding.noticeLayout.setVisibility(View.VISIBLE);
        }
        binding.noticeCloseImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.noticeLayout.setVisibility(View.GONE);
            }
        });


    }


    private void createGroup(){
        new XPopup.Builder(getContext())
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(true)
                .moveUpToKeyboard(false)
                .autoOpenSoftInput(false)
                .borderRadius(10)
                .atView(binding.getRoot())
                .asCustom(new ContactGroupSendDialog(getContext(),ContactChooseActivity.ContactChooseType.ContactChooseType_CreateSuperGroup, new ContactGroupSendDialog.OnItemClickListner() {

                    @Override
                    public void clickPostion(LocalMessageInfo messageInfo, GroupSendInfo groupSendInfo) {
                        if(messageInfo!=null&&groupSendInfo!=null){
//                            doGroupSend(groupSendInfo,messageInfo);
                        }
                    }
                })).show();
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.resetChatList();
    }

    @Override
    public void onResume() {
        super.onResume();
        //启动保活服务
        if (NotificationManagerCompat.from(mContext).areNotificationsEnabled()) {
            App.getInstanse().startKeepLiveService();
            binding.noticeLayout.setVisibility(View.GONE);
        }
        recentMessageListAdapter.notifyDataSetChanged();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x110 && data != null) {
            UserInfo userInfo = (UserInfo) data.getParcelableExtra("user");
            if (userInfo != null) {
                TelegramManager.getTelegramManager().createPrivateChat(getContext(), userInfo.id, new TgResultBlock<ChatInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                        if (obj != null) {
                            ChatActivity.startActivity(getContext(), obj);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        ToastUtils.showShort(getString(R.string.request_error));
                    }
                });
            }
        }
    }


    private long lastedFindChatId = -1;
    private int lastedFindChatCount = -1;

    @Override
    public void doubleClick() {
        List<ChatInfo> chatList = viewModel.chatList.get();
        int findPosition = -1;
        int unReadIndex = 0;
        if (chatList != null && chatList.size() > 0) {
            for (int i = 0; i < chatList.size(); i++) {
                ChatInfo chatInfo = chatList.get(i);
                if (chatInfo.unread_count > 0) {
                    unReadIndex++;
                    if (lastedFindChatId != chatInfo.id && unReadIndex > lastedFindChatCount && findPosition == -1) {
                        lastedFindChatId = chatInfo.id;
                        findPosition = i;
                        lastedFindChatCount = unReadIndex;
                    }
                }
            }

            if (unReadIndex == lastedFindChatCount || findPosition == -1) {
                lastedFindChatCount = -1;
                lastedFindChatId = -1;
            }

        }
        if (findPosition <= 0) {
            lastedFindChatId = -1;
            binding.scrollView.smoothScrollTo(0, 0);
        } else {
            View view = linearLayoutManager.findViewByPosition(findPosition);
            if (view != null) {
                int[] location = new int[2];
                view.getLocationInWindow(location);
                int position = location[1] - binding.toolbar.rlToolbar.getHeight() - ImmersionBar.getStatusBarHeight(this);
                binding.scrollView.smoothScrollBy(0, position);
            }
        }
    }
}